<?php


namespace App\Http\Controllers\Backend;

use App\Businesses\BusinessState;
use App\Services\Base\Interfaces\ConfigServiceInterface;
use App\Services\Base\Services\ConfigService;
use App\Services\Business\Interfaces\AppraiseServiceInterface;
use App\Services\Business\Interfaces\VideoServiceInterface;
use App\Services\Business\Models\Appraise;
use App\Services\Business\Models\Article;
use App\Services\Business\Services\AppraiseService;
use App\Services\Business\Services\VideoService;
use App\Services\Member\Interfaces\RoleServiceInterface;
use App\Services\Member\Interfaces\SocialiteServiceInterface;
use App\Services\Member\Interfaces\UserServiceInterface;
use App\Services\Member\Models\CompanyUser;
use App\Services\Member\Services\DeliverService;
use App\Services\Member\Services\RoleService;
use App\Services\Member\Services\SocialiteService;
use App\Services\Member\Services\UserService;
use App\Services\Order\Interfaces\OrderServiceInterface;
use App\Services\Order\Services\OrderService;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Services\Member\Models\Role;
use App\Services\Member\Models\User;
use App\Services\Order\Models\Order;
use Illuminate\Support\Facades\Hash;
use App\Services\Business\Models\Video;
use App\Services\Member\Models\UserTag;
use App\Services\Member\Models\UserRemark;
use App\Services\Member\Models\UserProfile;
use App\Http\Requests\Backend\MemberRequest;
use App\Services\Member\Models\UserCreditRecord;
use App\Services\Member\Models\UserJoinRoleRecord;

use App\Services\Member\Notifications\SimpleMessageNotification;


class MemberController extends BaseController
{
    /**
     * @var UserService
     */
    protected $userService;

    /**
     * @var VideoService
     */
    protected $videoService;

    /**
     * @var RoleService
     */
    protected $roleService;
    /**
     * @var OrderService
     */
    protected $orderService;
    /**
     * @var SocialiteService
     */
    protected $socialiteService;

    protected $businessState;
    /**
     * @var ConfigService
     */
    protected $configService;
    /**
     * @var DeliverService
     */
    protected $deliverService;

    /**
     * @var AppraiseService
     */
    protected $appraiseService;

    public function __construct(
        UserServiceInterface      $userService,
        VideoServiceInterface     $videoService,
        RoleServiceInterface      $roleService,
        OrderServiceInterface     $orderService,
        SocialiteServiceInterface $socialiteService,
        BusinessState             $businessState,
        AppraiseServiceInterface  $appraiseService,
        ConfigServiceInterface    $configService
    )
    {
        $this->userService = $userService;
        $this->videoService = $videoService;
        $this->roleService = $roleService;
        $this->orderService = $orderService;
        $this->socialiteService = $socialiteService;
        $this->businessState = $businessState;
        $this->configService = $configService;

        $this->appraiseService = $appraiseService;

    }


    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function index(Request $request)
    {


        $keywords = $request->input('keywords', '');
        $members = User::query()
            ->when($keywords, function ($query) use ($keywords) {
                $userIds = User::query()->where('nick_name', 'like', '%' . $keywords . '%')
                    ->orWhere('mobile', $keywords)->select(['id'])->get()->pluck('id');
                $query->whereIn('user_id', $userIds);

            })

            ->orderBy('created_at', 'desc')
            ->paginate($request->input('size', 10));

        return $this->successData(compact('members'));
    }

    /**
     * 手动绑定评价
     * @param Request $request
     * @return JsonResponse
     */
    public function bindAppraise(Request $request)
    {

        $type = $request->input('type');
        $resourceId = $request->input('resource_id');
        $userId = $request->input('user_id');
        $appraiseId = $request->input('appraise_id');
        $modal = 'App\Services\Business\Models\\' . ucfirst($type);
        $modal = new $modal;
        $resource = $modal::find($resourceId);
        if ($resource->appraises()->where('user_id', $userId)->exists()) {
            return $this->error(__('用户已评价过,不需要再评价'));
        }
        if (!$appraise = Appraise::query()->where('id', $appraiseId)->where('is_used', -1)->first()) {
            return $this->error(__('此模板评价已使用过'));
        }

        $appraise->is_used = 1;
        $appraise->user_id = $userId;
        $resource->appraises()->save($appraise);
        $this->appraiseService->changeStatus($type, $resourceId, [$userId]);
        return $this->success(__('评价绑定成功'));


    }

    /**
     * 批量生成评价
     * @param Request $request
     * @param $type
     * @param $resourceId
     * @return JsonResponse
     */
    public function generateAppraise(Request $request, $type, $resourceId)
    {
        $userIds = $request->input('user_ids');
        $modal = 'App\Services\Business\Models\\' . ucfirst($type);
        $modal = new $modal;
        $resource = $modal::find($resourceId);
        //处理已经评价过的用户
        $alreadyAppraiseUserIds = $resource->appraises()->whereIn('user_id', $userIds)->select('user_id')->pluck('user_id')->toArray();
        $toAppraiseUserIds = array_values(array_diff($userIds, $alreadyAppraiseUserIds));
        $appraises = Appraise::query()->whereNull('appraiseable_id')->take(count($toAppraiseUserIds))->get();
        if ($appraises->count() <= 0) {
            return $this->error(__('评价库存模板不足'));
        }
        //剩余评价的模板库存不多
        if (count($appraises) < count($toAppraiseUserIds)) {
            $toAppraiseUserIds = array_slice($toAppraiseUserIds, 0, count($appraises) - count($toAppraiseUserIds));
        }
        foreach ($appraises as $key => $appraise) {
            $appraise->user_id = $toAppraiseUserIds[$key];
            $resource->appraises()->save($appraise);
        }
        $this->appraiseService->changeStatus($type, $resourceId, $toAppraiseUserIds);

        return $this->success(__('生成评价成功'));
    }






    public function create()
    {
        $roles = Role::query()->select(['id', 'name'])->orderByDesc('id')->get();
        $tags = UserTag::query()->select(['id', 'name'])->orderByDesc('id')->get();
        return $this->successData(compact('roles', 'tags'));
    }

    public function edit($id)
    {
        $member = User::query()
            ->with(['tags:id,name', 'remark:user_id,remark'])
            ->where('id', $id)
            ->firstOrFail();

        return $this->successData($member);
    }

    public function store(MemberRequest $request)
    {
        User::create($request->filldata());

        return $this->success();
    }


    public function update(Request $request, $id)
    {
        $user = User::query()->where('id', $id)->firstOrFail();
        $data = $request->only([
            'avatar', 'nick_name', 'mobile', 'password',
            'is_lock', 'is_active', 'role_id', 'expired_at',
            'invite_user_id', 'invite_balance', 'invite_user_expired_at',
        ]);

        $profileData = $request->only([
            'real_name', 'gender', 'age', 'birthday', 'profession', 'address', 'graduated_school', 'diploma',
            'id_number', 'id_frontend_thumb', 'id_backend_thumb', 'id_hand_thumb',
        ]);
        if ($profileData) {
            $profileData['real_name'] = $profileData['real_name'] ?? '';
            $profileData['gender'] = $profileData['gender'] ?? '';
            $profileData['age'] = $profileData['age'] ?? 0;
            $profileData['birthday'] = $profileData['birthday'] ?? '';
            $profileData['profession'] = $profileData['profession'] ?? '';
            $profileData['address'] = $profileData['address'] ?? '';
            $profileData['graduated_school'] = $profileData['graduated_school'] ?? '';
            $profileData['diploma'] = $profileData['diploma'] ?? '';
            $profileData['id_number'] = $profileData['id_number'] ?? '';
            $profileData['id_frontend_thumb'] = $profileData['id_frontend_thumb'] ?? '';
            $profileData['id_backend_thumb'] = $profileData['id_backend_thumb'] ?? '';
            $profileData['id_hand_thumb'] = $profileData['id_hand_thumb'] ?? '';
        }

        // 手机号校验
        if (User::query()->where('mobile', $data['mobile'])->where('id', '<>', $user['id'])->exists()) {
            return $this->error(__('手机号已存在'));
        }
        // 昵称校验
        if (User::query()->where('nick_name', $data['nick_name'])->where('id', '<>', $user['id'])->exists()) {
            return $this->error(__('昵称已经存在'));
        }

        // 字段默认值
        $data['role_id'] = (int)($data['role_id'] ?? 0);
        $data['expired_at'] = $data['expired_at'] ?? null;
        // 时间格式不允许空字符串
        $data['expired_at'] = $data['expired_at'] ?: null;
        // 如果删除了时间，那么将roleId重置为0
        $data['expired_at'] || $data['role_id'] = 0;
        // 如果roleId为0的话，那么expired_at也重置为null
        $data['role_id'] || $data['expired_at'] = null;
        // 修改密码
        ($data['password'] ?? '') && $data['password'] = Hash::make($data['password']);

        $user->fill($data)->save();

        // UserProfile
        if ($profileData) {
            $userProfile = UserProfile::query()->where('user_id', $id)->first();
            if ($userProfile) {
                $userProfile->save($profileData);
            } else {
                UserProfile::create(array_merge($profileData, ['user_id' => $id]));
            }
        }

        return $this->success();
    }

    public function detail($id)
    {
        $companyId = $this->loginCompanyId();
        $user = User::query()
            ->with([
                'role:id,name',
                'roles' => function ($query) use ($companyId) {
                    $query->wherePivot('company_id', $companyId);
                },
                'invitor:id,nick_name,mobile,avatar',
                'profile', 'tags:id,name',
                'remark:user_id,remark',
            ])
            ->where('id', $id)
            ->firstOrFail();

        return $this->successData([
            'data' => $user,
        ]);
    }







    // 积分记录
    public function credit1Records(Request $request, $id)
    {
        $records = UserCreditRecord::query()
            ->where('user_id', $id)
            ->where('field', 'credit1')
            ->orderByDesc('id')
            ->paginate($request->input('size', 20));
        return $this->successData([
            'data' => $records,
        ]);
    }

    // 积分变动
    public function credit1Change(Request $request)
    {
        $userId = $request->input('user_id');
        $credit1 = $request->input('credit1');
        $remark = $request->input('remark', '');
        DB::transaction(function () use ($userId, $credit1, $remark) {
            $user = User::query()->where('id', $userId)->firstOrFail();

            $user->credit1 += $credit1;
            $user->save();

            UserCreditRecord::create([
                'user_id' => $userId,
                'field' => 'credit1',
                'sum' => $credit1,
                'remark' => $remark,
            ]);
        });

        return $this->success();
    }

    public function userRoles(Request $request, $id)
    {
        $data = UserJoinRoleRecord::query()
            ->with(['role:id,name'])
            ->where('user_id', $id)
            ->orderByDesc('created_at')
            ->paginate($request->input('size', 20));


        return $this->successData([
            'data' => $data,
        ]);
    }

    public function tagUpdate(Request $request, $userId)
    {
        $tagIds = explode(',', $request->input('tag_ids', ''));

        $user = User::query()->where('id', $userId)->firstOrFail();

        $user->tags()->sync($tagIds);

        return $this->success();
    }

    // 用户备注
    public function remark($id)
    {
        $userRemark = UserRemark::query()->where('user_id', $id)->first();
        $remark = $userRemark ? $userRemark['remark'] : '';
        return $this->successData([
            'remark' => $remark,
        ]);
    }

    // 更新用户备注
    public function updateRemark(Request $request, $id)
    {
        $remark = $request->input('remark', '');
        $userRemark = UserRemark::query()->where('user_id', $id)->first();
        if ($userRemark) {
            $userRemark->update(['remark' => $remark]);
        } else {
            UserRemark::create([
                'user_id' => $id,
                'remark' => $remark,
            ]);
        }

        return $this->success();
    }

    public function sendMessageMulti(Request $request)
    {
        $message = $request->input('message');
        $userIds = $request->input('user_ids');

        if (!is_array($userIds) || !$userIds) {
            return $this->error('请选择需要发送消息的用户');
        }
        if (!$message) {
            return $this->error('请输入需要发送的消息');
        }
        if (count($userIds) > 100) {
            return $this->error('单次发送消息不能超过100人');
        }

        $users = User::query()->whereIn('id', $userIds)->get();
        foreach ($users as $user) {
            $user->notify(new SimpleMessageNotification($message));
        }

        return $this->success();
    }

    public function sendMessage(Request $request, $userId)
    {
        $user = User::query()->where('id', $userId)->firstOrFail();
        $message = $request->input('message');
        if (!$message) {
            return $this->error(__('参数错误'));
        }

        $user->notify(new SimpleMessageNotification($message));

        return $this->success();
    }

    public function userVideoWatchRecords(Request $request, $id)
    {
        $records = UserVideoWatchRecord::query()
            ->select([
                'id', 'user_id', 'course_id', 'video_id', 'watch_seconds', 'watched_at', 'created_at',
            ])
            ->where('user_id', $id)
            ->orderByDesc('id')
            ->paginate($request->input('size', 10));

        $videos = [];
        $videoIds = array_column($records->items(), 'video_id');
        if ($videoIds) {
            $videos = Video::query()->whereIn('id', $videoIds)->select(['id', 'title'])->get()->keyBy('id');
        }

        return $this->successData([
            'data' => $records,
            'videos' => $videos,
        ]);
    }

    public function import(Request $request)
    {

        $users = $request->input('users');
        if (!$users || !is_array($users)) {
            return $this->error(__('请导入数据'));
        }
        if (count($users) > 1000) {
            return $this->error(__('一次最多导入1000条数据'));
        }

        // 手机号重复检测
        $mobiles = array_column($users, 0);
        if (count(array_flip(array_flip($mobiles))) !== count($mobiles)) {
            return $this->error('手机号重复');
        }

        // VIP规范检测
        $roles = Role::query()->select(['id'])->get()->pluck('id')->toArray();
        $nowTime = time();
        foreach ($users as $userItem) {
            $roleId = (int)($userItem[2] ?? 0);
            $roleExpiredAt = $userItem[3] ?? null;
            // case1: 配置VIP-ID但是未配置VIP的过期时间
            if ($roleId && !$roleExpiredAt) {
                return $this->error(__('手机号[:mobile]配置了VIP但未配置过期时间', ['mobile' => $userItem[0] ?? '']));
            }
            // case2: 配置了VIP过期时间但是未配置VIP-ID
            if (!$roleId && $roleExpiredAt) {
                return $this->error(__('手机号[:mobile]配置了VIP过期时间但未配置VIP', ['mobile' => $userItem[0] ?? '']));
            }
            // case3: VIP-ID和VIP过期时间都配置了，但是过期时间小于当前时间
            if ($roleId && $roleExpiredAt && strtotime($roleExpiredAt) < $nowTime) {
                return $this->error(__('手机号[:mobile]的VIP过期时间小于当前时间', ['mobile' => $userItem[0] ?? '']));
            }
            // case4: VIP不存在
            if ($roleId && !in_array($roleId, $roles)) {
                return $this->error(__('手机号[:mobile]配置的VIP不存在', ['mobile' => $userItem[0] ?? '']));
            }
        }

        // 手机号存在检测
        foreach (array_chunk($mobiles, 500) as $item) {
            $exists = User::query()->whereIn('mobile', $item)->select(['mobile'])->get();
            if ($exists->isNotEmpty()) {
                return $this->error(sprintf(__('手机号%s已存在'), implode(',', $exists->pluck('mobile')->toArray())));
            }
        }

        // 标签处理
        $tags = [];
        foreach ($users as $userItem) {
            $tmpTagName = $userItem[5] ?? null;
            if (!$tmpTagName) {
                continue;
            }
            $tags = array_merge($tags, explode(',', $tmpTagName));
        }
        // 去重
        $tags = array_flip(array_flip($tags));
        // 读取已经存在的tag
        $existsTags = UserTag::query()->whereIn('name', $tags)->select(['id', 'name'])->get();
        // 筛选出未创建的tag
        $notExistsTags = array_diff($tags, $existsTags->pluck('name')->toArray());
        if ($notExistsTags) {
            // 批量插入
            $insertList = [];
            $now = Carbon::now()->toDateTimeLocalString();
            foreach ($notExistsTags as $tagName) {
                $insertList[] = ['name' => $tagName, 'created_at' => $now, 'updated_at' => $now];
            }
            UserTag::insert($insertList);
            // 读取新创建的tag
            $newTags = UserTag::query()->whereIn('name', $notExistsTags)->select(['id', 'name'])->get();
            $existsTags = $existsTags->merge($newTags);
        }
        $existsTags = $existsTags->keyBy('name')->toArray();
        foreach ($users as $key => $userItem) {
            $tmpTag = $userItem[5] ?? null;
            if (!$tmpTag) {
                $users[$key]['tag_ids'] = [];
                continue;
            }
            $tmpTags = explode(',', $tmpTag);
            $syncTagIds = [];
            foreach ($tmpTags as $tagName) {
                $syncTagIds[] = $existsTags[$tagName]['id'];
            }
            $users[$key]['tag_ids'] = $syncTagIds;
        }

        DB::transaction(function () use ($users) {
            $now = Carbon::now()->toDateTimeLocalString();
            foreach (array_chunk($users, 500) as $usersItem) {
                $data = [];
                if (!$usersItem) {
                    break;
                }

                // 批量插入用户
                foreach ($usersItem as $item) {
                    $tmpMobile = $item[0];
                    // 密码
                    $tmpPassword = $item[1];
                    // VIP处理l
                    $tmpRoleId = (int)($item[2] ?? 0);
                    $tmpRoleExpiredAt = $item[3] ?? null;
                    if ($tmpRoleExpiredAt) {
                        $tmpRoleExpiredAt = Carbon::parse($item[3])->toDateTimeLocalString();
                    }
                    // 是否锁定
                    $tmpIsLock = (int)($item[4] ?? 0);

                    $data[] = [
                        'mobile' => $tmpMobile,
                        'avatar' => url(config('zesow.member.default_avatar')),
                        'nick_name' => mb_substr($tmpMobile, 0, 8) . '_' . Str::random(5),
                        'is_active' => (int)config('zesow.member.is_active_default'),
                        'is_lock' => $tmpIsLock,
                        'password' => Hash::make($tmpPassword),
                        'is_password_set' => 0,
                        'is_set_nickname' => 0,
                        'is_used_promo_code' => 0,
                        'role_id' => $tmpRoleId,
                        'expired_at' => $tmpRoleExpiredAt,
                        'created_at' => $now,
                        'updated_at' => $now,
                    ];
                }
                User::insert($data);

                // 标签关联数据缓存
                $tagInsertList = [];
                $mobile2idMap = User::query()->whereIn('mobile', array_column($data, 'mobile'))->select(['id', 'mobile'])->get()->keyBy('mobile');
                foreach ($usersItem as $item) {
                    if (!$item['tag_ids']) {
                        continue;
                    }
                    $userId = $mobile2idMap[$item[0]]['id'];
                    foreach ($item['tag_ids'] as $tagId) {
                        $tagInsertList[] = [
                            'user_id' => $userId,
                            'tag_id' => $tagId,
                        ];
                    }
                }
                $tagInsertList && DB::table('user_tag_relation')->insert($tagInsertList);
            }
        });

        return $this->success();
    }

    public function updateFieldMulti(Request $request)
    {
        $userIds = $request->input('user_ids');
        if (!$userIds || !is_array($userIds)) {
            return $this->error('请选择需要修改的用户');
        }

        // 要更改的字段
        $field = $request->input('field');
        // 欲更改为的字段值
        $value = $request->input('value');
        // 如果更改为roleId的话则需要传递该参数
        $roleExpiredAt = $request->input('expired_at');
        // 如果修改的是标签的话则需要传递该参数
        $tagIds = $request->input('tag_ids');

        // 必须是白名单内的字段才可以更改
        $fieldsWhitelist = [
            'is_lock', 'is_active', 'role_id', 'expired_at', 'is_password_set', 'is_set_nickname',
            'tag',
        ];
        if (!$field || !in_array($field, $fieldsWhitelist)) {
            return $this->error('待修改字段不合法');
        }

        // 如果选择了有效的roleId的话，那么expired_at则必须是有效的时间
        if ($field === 'role_id' && (int)$value && !$roleExpiredAt) {
            return $this->error('请选择VIP过期时间');
        }

        if ($field === 'tag') {
            $tagIds = $tagIds && is_array($tagIds) ? $tagIds : [];
            $users = User::query()->whereIn('id', $userIds)->get();
            foreach ($users as $userItem) {
                $userItem->tags()->sync($tagIds);
            }
        } else {
            // 整数值字段，对即将修改的值进行取整处理
            $intFields = ['is_lock', 'is_active', 'is_password_set', 'is_set_nickname', 'role_id'];
            if (in_array($field, $intFields)) {
                $value = (int)$value;
            }
            $updateData[$field] = $value;

            if ($field === 'role_id') {
                $updateData['expired_at'] = Carbon::parse($roleExpiredAt)->toDateTimeLocalString();
            }

            User::query()->whereIn('id', $userIds)->update($updateData);
        }

        return $this->success();
    }


    /**添加课程
     * @param Request $request
     * @return JsonResponse
     */
    public function createSubscribe(Request $request): JsonResponse
    {
        $product = $request->input('product', []);
        $userIds = $request->input('user_ids');
        if (!is_array($userIds)) {
            $userIds = [$userIds];
        }
        if (!$product['goods_type'] || !$product['goods_id'] || !$userIds) {
            return $this->error(__('参数错误'));
        }
        $method = 'deliver' . ucfirst(strtolower($product['goods_type']));
        $this->deliverService->$method($userIds, $product);

        return $this->success(__('权限添加成功'));
    }
    /*
 *
 *
 *  删除订阅
 *
 * */
    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function deleteSubscribe(Request $request)
    {
        $companyId = $this->loginCompanyId();
        $resourceType = ucfirst($request->input('resourceType'));
        $resourceId = $request->input('resourceId');
        $userId = $request->input('userId');
        if (!$resourceId || !$resourceType || !$userId) {
            return $this->error(__('参数错误！'));
        }
        $model = 'App\Services\Business\Models\\' . $resourceType;
        $resource = $model::find($resourceId);
        if ($resource['company_id'] !== $companyId) {

            return $this->error(__('无权限删除权限'));
        }

        //课程权限删除
        DB::transaction(function () use ($resourceType, $resourceId, $userId, $resource) {
            $UserModel = 'App\Services\Member\Models\User' . $resourceType;
            $UserModel = new  $UserModel();
            $UserModel::query()->where(strtolower($resourceType) . '_id', $resourceId)->where('user_id', $userId)->delete();
            // 课程订阅数量更新
            $resource->decrement('user_count');
        }
        );


        return $this->success(__('删除权限成功'));
    }

    public function importSubscribes(Request $request)
    {

        $items = $request->input('items');
        $resourceType = $request->input('resource_type');
        $resourceId = $request->input('resource_id');
        if (!$items || !is_array($items)) {

            return $this->error(__('请导入数据'));
        }
        if (count($items) > 1000) {
            return $this->error(__('一次最多导入1000条数据'));
        }


        $mobiles = array_column($items, 0);
        //已经存在手机号
        $existMobiles = User::query()->whereIn('mobile', $mobiles)->pluck('mobile', 'id')->toArray();
        //去掉已经存在的手机号，只生成未注册的手机账户
        $items = array_diff($mobiles, array_values($existMobiles));
        DB::transaction(function () use ($items, $resourceType, $resourceId, $existMobiles) {
            $now = Carbon::now()->toDateTimeLocalString();
            $batchCode = Str::random(5);
            foreach (array_chunk($items, 500) as $mobileItems) {
                $data = [];
                if (!$mobileItems) {
                    break;
                }
                // 批量插入用户
                foreach ($mobileItems as $item) {
                    $mobile = $item;
                    $data[] = [
                        'mobile' => $mobile,
                        'avatar' => url(config('zesow.member.default_avatar')),
                        'nick_name' => mb_substr($mobile, 0, 8) . '_' . Str::random(5),
                        'is_active' => (int)config('zesow.member.is_active_default'),
                        'is_lock' => 0,
                        'password' => Hash::make($mobile),
                        'is_password_set' => 0,
                        'is_set_nickname' => 0,
                        'is_used_promo_code' => 0,
                        'batch_code' => $batchCode,
                        'created_at' => $now,
                        'updated_at' => $now,
                    ];
                }
                User::insert($data);

            }
            //这里只获取已经本批次插入有batch_code的数据，优化查询+已经存在系统的注册用户的userId
            $userIds = array_merge(array_keys($existMobiles), User::query()->where('batch_code', $batchCode)->pluck('id')->toArray());
            $model = 'App\Services\Business\Models\\' . ucfirst($resourceType);
            $model = new $model();
            $model = $model::find($resourceId);
            $model->member()->attach($userIds);
        });


        return $this->success(__('批量改入用户成功'));

    }

    public function createSubscribeByMobile(Request $request)
    {
        $mobile = $request->input('mobile', '');
        $product = $request->input('product', []);
        if (!$product['goods_type'] || !$product['goods_id'] || !$mobile) {
            return $this->error(__('参数错误'));
        }
        $user = $this->userService->findMobile($mobile);
        if (!$user) {
            $user = $this->userService->createWithMobile($mobile, '', '', '');
        }

        $method = 'deliver' . ucfirst(strtolower($product['goods_type']));
        $this->deliverService->$method($user['id'], $product);

        return $this->success(__('学习权限添加成功'));
    }


    public function subscribes(Request $request, string $type, int $id)
    {


        $size = $request->input('size', 10);
        $keywords = $request->input('keywords', '');
        $isExpired = $request->input('is_expired', 0);
        $isAppraised = $request->input('is_appraised', 0);
        $expiredId = $request->input('expired_id', 0);
        $model = 'App\Services\Member\Models\User' . ucfirst($type);
        $model = new $model();

        $userIds = [];
        if ($keywords) {
            $userIds = User::query()
                ->when($keywords, function ($query) use ($keywords) {
                    $query->where('nick_name', 'like', '%' . $keywords . '%')
                        ->orWhere('mobile', $keywords)
                        ->orWhere('uuid', $keywords);
                })
                ->select(['id'])->get()->pluck('id')->toArray();
        }
        // 课程订阅数量更新
        $members = $model::query()
            ->with(['member:id,uuid,nick_name,avatar,mobile'])
            ->when($isExpired, function ($query) use ($isExpired) {
                $query->where('expired_at', $isExpired == 1 ? '<' : '>', Carbon::now());

            })
            ->when($isAppraised, function ($query) use ($isAppraised) {
                $query->where('is_appraised', $isAppraised);

            })
            ->when($keywords, function ($query) use ($userIds) {
                $query->whereIn('user_id', $userIds);
            })
            ->when($expiredId, function ($query) use ($expiredId) {
                $query->where('expired_id', $expiredId);
            })
            ->where($type . '_id', $id)
            ->orderBy('created_at')
            ->paginate($size);
        return $this->successData(compact('members'));

    }

    /**
     * 所有创作老师
     * @param Request $request
     * @return JsonResponse
     */
    public function employees(Request $request)
    {


        $categories = $request->input('categories', []);
        $years = $request->input('work_years', []);
        $isFulltime = $request->input('is_fulltime', 0);
        $sort = $request->input('sort', 'id');
        $order = $request->input('order', 'desc');

        $employees = UserProfile::query()
            ->with(['user'])
            ->when($categories, function ($query) use ($categories) {
                return $query->whereIn('category_id', $categories ?? []);
            })
            ->when($years, function ($query, $years) {
                return $query->where(function ($subquery) use ($years) {
                    foreach ($years as $range) {
                        $subquery->orWhereBetween('work_years', $range);
                    }
                });
            })
            ->when($isFulltime, function ($query) use ($isFulltime) {
                return $query->where('is_fulltime', $isFulltime);
            })
            ->where('is_employee', 1)
            ->orderBy($sort, $order)
            ->paginate($request->input('size', 10));


        return $this->successData(compact('employees'));

    }

    /**
     * 创作收益
     * @param $id
     * @return JsonResponse
     */
    public function employee($id)
    {


        // 本月收益
        $thisMonthPaidSum = (int)Order::query()
            ->where('created_at', '>=', date('Y-m') . '-01')
            ->where('status', Order::STATUS_PAID)
            ->sum('charge');
        // 上个月收益
        $lastMonthPaidSum = (int)Order::query()
            ->whereBetween('created_at', [Carbon::now()->subMonths(1)->format('Y-m') . '-01', date('Y-m') . '-01'])
            ->where('status', Order::STATUS_PAID)
            ->sum('charge');

        //本月文章数
        $thisMonthCreatedArticleCount = (int)Article::query()
            ->where('created_at', '>=', date('Y-m') . '-01')
            ->where('user_id', $id)
            ->count();
        // 上个月创作视频数
        $lastMonthCreatedArticleCount = (int)Article::query()
            ->whereBetween('created_at', [Carbon::now()->subMonths(1)->format('Y-m') . '-01', date('Y-m') . '-01'])
            ->where('user_id', $id)
            ->count();

        //本月创作视频数
        $thisMonthCreatedVideoCount = (int)Video::query()
            ->where('created_at', '>=', date('Y-m') . '-01')
            ->where('user_id', $id)
            ->count();
        // 上月创作视频数
        $lastMonthCreatedVideoCount = (int)Video::query()
            ->whereBetween('created_at', [Carbon::now()->subMonths(1)->format('Y-m') . '-01', date('Y-m') . '-01'])
            ->where('user_id', $id)
            ->count();

        //本月创作视频数
        $thisMonthCreatedDoubtCount = (int)Doubt::query()
            ->where('created_at', '>=', date('Y-m') . '-01')
            ->where('author_id', $id)
            ->count();
        // 上月创作视频数
        $lastMonthCreatedDoubtCount = (int)Doubt::query()
            ->whereBetween('created_at', [Carbon::now()->subMonths(1)->format('Y-m') . '-01', date('Y-m') . '-01'])
            ->where('author_id', $id)
            ->count();


        return $this->successData([

            // 月度收益
            'this_month_paid_sum' => $thisMonthPaidSum,
            'last_month_paid_sum' => $lastMonthPaidSum,

            // 月度文章创作数
            'this_month_created_article_count' => $thisMonthCreatedArticleCount,
            'last_month_created_article_count' => $lastMonthCreatedArticleCount,


            // 月度视频创作数
            'this_month_created_video_count' => $thisMonthCreatedVideoCount,
            'last_month_created_video_count' => $lastMonthCreatedVideoCount,


            // 月度解惑创作数
            'this_month_created_doubt_count' => $thisMonthCreatedDoubtCount,
            'last_month_created_dobut_count' => $lastMonthCreatedDoubtCount,
        ]);
    }

    public function employeeChart(Request $request, $id)
    {

        $startAt = $request->input('start_at');
        $endAt = $request->input('end_at');
        if (!$startAt || !$endAt) {
            return $this->error(__('参数错误'));
        }
        $startAt = Carbon::parse($startAt)->format('Y-m-d');
        $endAt = Carbon::parse($endAt)->addDay()->format('Y-m-d');
        $endAtCarbon = Carbon::parse($endAt);


        // 每日创作文章数量统计
        $createdArticles = [];
        // 每日创作视频数量统计
        $createdVideos = [];
        // 每日解惑数量统计
        $createdDoubts = [];


        // 每日支付总额统计
        $orderSum = [];

        $tmpAt = Carbon::parse($startAt);

        while ($endAtCarbon->gt($tmpAt)) {
            $tmpKey = $tmpAt->format('Y-m-d');

            $orderSum[$tmpKey] = 0;
            $createdArticles[$tmpKey] = 0;
            $createdVideos[$tmpKey] = 0;
            $createdDoubts[$tmpKey] = 0;

            $tmpAt->addDays();
        }

        //文章数
        $articles = Article::query()
            ->select(['created_at'])
            ->where('user_id', $id)
            ->whereBetween('created_at', [$startAt, $endAt])
            ->get();
        foreach ($articles as $tmpVal) {
            $tmpDate = Carbon::parse($tmpVal['created_at'])->format('Y-m-d');
            $createdArticles[$tmpDate]++;
        }
        //视频数
        $videos = Video::query()
            ->select(['created_at'])
            ->where('user_id', $id)
            ->whereBetween('created_at', [$startAt, $endAt])
            ->get();
        foreach ($videos as $tmpVal) {
            $tmpDate = Carbon::parse($tmpVal['created_at'])->format('Y-m-d');
            $createdVideos[$tmpDate]++;
        }


        //解惑数
        $doubts = Doubt::query()
            ->select(['created_at'])
            ->where('author_id', $id)
            ->whereBetween('created_at', [$startAt, $endAt])
            ->get();
        foreach ($doubts as $tmpVal) {
            $tmpDate = Carbon::parse($tmpVal['created_at'])->format('Y-m-d');
            $createdDoubts[$tmpDate]++;
        }

        $paidOrders = Order::query()
            ->select(['created_at', 'charge'])
            ->where('status', Order::STATUS_PAID)
            ->whereBetween('created_at', [$startAt, $endAt])
            ->get();
        foreach ($paidOrders as $tmpVal) {
            $tmpDate = Carbon::parse($tmpVal['created_at'])->format('Y-m-d');
            $orderSum[$tmpDate] += $tmpVal['charge'];
        }

        return $this->successData([
            'order_sum' => $orderSum,
            'created_articles' => $createdArticles,
            'created_videos' => $createdVideos,
            'created_doubts' => $createdDoubts
        ]);


    }



}
